<template>
  <div class="housing-lease-management">
    <!-- 操作栏：添加按钮 + 搜索 -->
    <div class="operation-bar">
      <el-button type="success" icon="el-icon-plus" @click="handleAdd">添加合同</el-button>
      <div class="search-group" style="margin-left: auto;">
        <el-input v-model="searchQuery" placeholder="请输入姓名/房号/手机号搜索" style="width: 240px;" />
        <el-button type="primary" icon="el-icon-search" @click="handleSearch"></el-button>
        <el-button type="primary" icon="el-icon-filter"></el-button>
      </div>
    </div>

    <!-- 房屋合同表格 -->
    <el-table :data="filteredTableData" border style="width: 100%; margin-bottom: 20px;">
      <el-table-column prop="communityName" label="所属小区" />
      <el-table-column prop="roomNumber" label="房号" />
      <el-table-column prop="roomArea" label="面积(㎡)" width="100" />
      <el-table-column prop="orientation" label="朝向" width="100" />
      <el-table-column prop="leaseName" label="租赁方" />
      <el-table-column prop="tenantName" label="联系人" width="100" />
      <el-table-column prop="tenantPhone" label="联系电话" />
      <el-table-column prop="contractRent" label="租金" width="100" />
      <el-table-column prop="startDate" label="起租时间" />
      <el-table-column prop="depositName" label="租金方式" />
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleDetail(scope.row)">详情</el-button>
          <el-button type="danger" size="small" plain @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrap">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[5, 10, 15]" :page-size="pageSize" :total="total"
        layout="prev, pager, next, ->, jumper, ->, sizes, total" />
    </div>
  </div>
</template>

<script>
import request from '@/utils/request';

export default {
  name: 'HousingLease',
  data() {
    return {
      searchQuery: '',
      tableData: [],
      filteredTableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0
    }
  },
  created() {
    this.fetchContracts();
  },
  methods: {
    fetchContracts() {
      request.post('/roomLease/getRoomLeaseList', {
        page: this.currentPage,
        size: this.pageSize
      })
        .then(res => {
          this.tableData = res.data.records || [];
          this.total = res.data.total || 0;
          this.filterTableData();
        })
        .catch(err => {
          this.$message.error('获取合同列表失败');
          console.error(err);
        });
    },
    handleAdd() {
      this.$router.push({
        name: 'AddRoomLease',
        query: {
          action: 'add'
        }
      });
    },
    handleDetail(row) {
      this.$router.push({
        name: 'RoomLeaseDetail',
        query: {
          id: row.roomLeaseId
        }
      });
    },
    handleEdit(row) {
      this.$router.push({
        name: 'AddRoomLease',
        query: {
          action: 'edit',
          id: row.roomLeaseId
        }
      });
    },
    handleDelete(row) {
      this.$confirm('确定要删除该合同吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.delete(`/roomLease/deleteRoomLease`, {
          data: { roomLeaseId: row.roomLeaseId }
        })
          .then(res => {
            if (res.code === 200) {
              this.$message.success('合同删除成功');
              this.fetchContracts();
            } else {
              this.$message.error(res.message || '删除失败');
            }
          })
          .catch(err => {
            this.$message.error('删除过程中发生错误');
            console.error(err);
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handleSearch() {
      this.filterTableData();
    },
    filterTableData() {
      if (this.searchQuery) {
        this.filteredTableData = this.tableData.filter(item => {
          return item.communityName.includes(this.searchQuery) ||
            item.roomNumber.includes(this.searchQuery) ||
            item.tenantName.includes(this.searchQuery) ||
            (item.tenantPhone && item.tenantPhone.includes(this.searchQuery));
        });
      } else {
        this.filteredTableData = this.tableData;
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchContracts();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchContracts();
    }
  }
}
</script>

<style scoped>
.housing-lease-management {
  padding: 20px;
}

.operation-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.search-group {
  display: flex;
  align-items: center;
}

.search-group .el-input {
  margin-right: 8px;
}

.pagination-wrap {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
